<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2019-10-21
 * Time: 23:21
 */

namespace app\api\controller;
use app\common\controller\ApiController;
use think\Db;
class Parking extends ApiController
{
   
    public function index(){
        echo 111;die;
    }
    // 获取车位列表
    public function getList() {
        $param = $this->request->param();
        if(@$param['bd_info_id']) $where[]=['bd_info_id','=',$param['bd_info_id']];
        if(@$param['status']) $where[]=['status','=',$param['status']];
        $where[] = ['c.is_deleted','=',0];
        if(!empty($param['name'])) $where[] = ['c.name','like','%'.$param['name'].'%'];
        if(!empty($this->userinfo['cm_message_id'])){
            if (@$param['cm_message_id']) {
                $where[] = ['bd.id','in',$param['cm_message_id']];
            } else {
                $where[] = ['bd.id','in',$this->userinfo['cm_message_id']];
            }
        }
        $list = Db::name('wy_car_area c')
            ->join('wy_bd_info bd','c.bd_info_id = bd.id')
            ->where($where)
            ->field('c.*,bd.name bd_name')
            ->page($param['pageNo'],$param['pageSize'])
            ->order('c.id','desc')->select();
        foreach ($list as $k=>$v){
            $list[$k]['bz_number'] = Db::name('wy_toll_bz_middle')->alias('m')
                ->join('wy_toll_project p','m.project_id = p.id')
                ->join('wy_toll_project_detial d','m.project_detail_id = d.id')
                ->where(['houses_id'=>$v['id'],'type'=>2])->count();
        }
        $count = Db::name('wy_car_area c')
            ->join('wy_bd_info bd','c.bd_info_id = bd.id')
            ->where($where)->count();
        return __success('ok',['data'=>$list,'pageSize'=>$param['pageSize'],'pageNo'=>$param['pageNo'],'totalCount'=>$count,'totalPage'=>ceil($count / $param['pageSize'])]);
    }

    // 添加or编辑车位
    public function operation() {
        $param = $this->request->param();
        unset($param['token']);
        if(empty($param['bd_info_id'])) return __error('所属小区不可为空');
        if(empty($param['name'])) return __error('车位号不可为空');
        if(empty($param['area'])) return __error('产权面积不可为空');
        if(empty($param['type'])) return __error('车位类型不可为空');
        if(empty($param['status'])) return __error('车位状态不可为空');
        // 查询车位信息->防止车位号重复
        $carMap[] = ['name','=',$param['name']];
        $carMap[] = ['bd_info_id','=',$param['bd_info_id']];
        $carMap[] = ['is_deleted','=',0];
        if($param['id'] !== 0) $carMap[] = ['id','<>',$param['id']];
        $houseInfo = Db::name('wy_car_area')->where($carMap)->find();
        if(!empty($houseInfo)) return __error('车位号重复');
        if($param['id'] == 0){
            $id = Db::name('wy_car_area')->strict(false)->insert($param,true,true);
            return __success('添加成功',$id);
        }else{
            $upRes = Db::name('wy_car_area')->update($param);
            return $upRes !== false ? __success('保存成功',$param['id']) : __error('保存失败');
        }
    }

    // 绑定用户
    public function bindUser() {
        $param = $this->request->param();
        $data = array();
        foreach ($param['house_user_id'] as $key=>$value) array_push($data,['house_user_id'=>$value,'car_area_id'=>$param['car_area_id'],'middle_type'=>2]);
        $findIsBind = Db::name('wy_houses_user_middle')->where(['house_user_id'=>['in',implode(',',$param['house_user_id'])],'car_area_id'=>$param['car_area_id']])->find();
        if(!empty($findIsBind)) return __error('请勿重复绑定');
        $addRes = Db::name('wy_houses_user_middle')->insertAll($data);
        return $addRes ? __success('绑定成功') : __error('绑定失败');
    }

    // 获取可绑定住户
    public function getBindUserList() {
        $id = $this->request->param('id'); // 车位id
        $bd_info_id = $this->request->param('bd_info_id'); // 小区id
        $text = $this->request->param('text'); // 搜索
        $type = intval($this->request->post('type'));
        if(empty($text)) return __success('ok',[]);
        if(mb_strlen($text) < 2) return __success('ok',[]);
        // 当前车位已关联住户
        $middleUser = Db::name('wy_houses_user_middle')->where('car_area_id',$id)->column('house_user_id');
        $map = 'status in(1,4)';
        if(!empty($middleUser)){
            $map .= ' and id not in ('.implode(',',$middleUser).')';
        }
        if ($text) {
            if ($type == 1) {
                $map .= ' and (license like \''.$text.'%\' )';
            } else {
                $hids = Db::name('wy_houses')->where('name','like','%'.$text.'%')->column('id');
                if ($hids) {
                    $map .= ' and (phone like \''.$text.'%\' or name like \''.$text.'%\' or houses_id in ('.implode(',',$hids).'))';
                } else {
                    $map .= ' and (phone like \''.$text.'%\' or name like \''.$text.'%\' )';
                }
            }
        }
        $list = Db::name('wy_house_user')->where($map)->field('id value,bd_info_id,building_id,houses_id,name,phone,status')->limit(20)->group('phone')->order('houses_id desc')->select();
        foreach ($list as $key=>$value){
            $bd_info_text = Db::name('wy_bd_info')->where('id',$value['bd_info_id'])->value('name');
            // $building_text = Db::name('wy_building')->where('id',$value['building_id'])->value('name');
            $houses_text = Db::name('wy_houses')->where('id',$value['houses_id'])->value('name');
            if ($value['status'] == 4) {
                $list[$key]['label'] =  '非住户'.'-'.$value['name'].'-'.$value['phone'];
            } else {
                if($bd_info_text && $houses_text){
                    $list[$key]['label'] =  $bd_info_text.'-'.$houses_text.'-'.$value['name'].'-'.$value['phone'];
                }else{
                    $list[$key]['label'] =  '非住户'.'-'.$value['name'].'-'.$value['phone'];
                }
                
            }
        }
        return __success('ok',$list);
    }

    // 获取小区车位
    public function getParkingTree(){
        $param = $this->request->param();
        $where[] = ['is_deleted','=',0];
        $where[] = ['pms_ar_id','=',$this->userinfo['pms_ar_id']];
        if($this->userinfo['cm_message_id']){
            $where[] = ['id','in',$this->userinfo['cm_message_id']];
        }
        // 小区
        $communityList = Db::name('wy_bd_info')->where($where)->field('id value,name label')->select();
        
        $communityIds = array();
        foreach ($communityList as $key=>$value) array_push($communityIds,$value['value']);
        // 车位
        $carAreaList = Db::name('wy_car_area')->where('bd_info_id','in',$communityIds)->where(['is_deleted'=>0])->field('id value,name label,bd_info_id')->select();
        // 拼装数据
        $allData = array();
        foreach ($communityList as $ck=>$cv){
            $cv['children'] = array();
            $cv['title']=$cv['label'];
            $cv['key']=$cv['value'];
            foreach ($carAreaList as $bk=>$bv){
                $bv['title']=$bv['label'];
                $bv['key']=$bv['value'];
                if($bv['bd_info_id'] === $cv['value']) {
                    unset($bv['bd_info_id']);
                    array_push($cv['children'],$bv);
                }
            }
            if(!empty($cv['children'])) array_push($allData,$cv);
        }
        return __success('ok',$allData);
    }
    // 获取车位信息
    public function getInfo() {
        $id = $this->request->param('id');
        if(empty($id)) return __error('参数错误');
        $info = Db::name('wy_car_area c')
            ->join('wy_bd_info b','c.bd_info_id = b.id')
            ->leftJoin('wy_labels l','c.labels_id = l.id')
            ->where('c.id',$id)->field('c.*,b.name bd_name,l.name label_name')->find();
        // 相关住户
        $houseUser = Db::name('wy_houses_user_middle')->alias('m')
            ->join('wy_house_user u','m.house_user_id = u.id')
            ->join('wy_bd_info bd','u.bd_info_id = bd.id')
            ->join('wy_building b','u.building_id = b.id')
            ->join('wy_unit un','u.unit_id = un.id')
            ->join('wy_houses h','u.houses_id = h.id')
            ->leftJoin('wy_labels l','u.labels_id = l.id')
            ->where(['m.car_area_id'=>$info['id']])->field('u.id,u.name,u.phone,bd.name bd_name,b.name building_name,un.name unit_name,h.name houses_name,l.name label_name')->order('m.id desc')->select();
        $houseUserIds=[];
        foreach($houseUser as $k=>$v){
            $houseUserIds[]=$v['id'];
        }
        if($houseUserIds){
            // 相关车辆
            $car = Db::name('wy_car')->alias('c')
            ->join('wy_houses_user_middle m','m.car_id=c.id')
            ->join('wy_bd_info b','c.bd_info_id = b.id')
            ->leftJoin('wy_labels l','c.labels_id = l.id')
            ->where([['m.house_user_id','in',$houseUserIds],['c.is_deleted','=',0]])->field('c.id,c.name,b.name bd_name,c.username,c.phone,l.name label_name')->order('c.id desc')->select();
        }else{
            $car=[];
        }
        
        // 相关收费标准
        $tollBz = Db::name('wy_toll_bz_middle')->alias('m')
            ->join('wy_toll_project p','m.project_id = p.id')
            ->join('wy_toll_project_detial d','m.project_detail_id = d.id')
            ->where(['m.houses_id'=>$id,'type'=>2])
            ->field('m.id,p.name project_name,d.name project_detail_name,DATE_FORMAT(m.start_time,"%Y-%m-%d") start_time,DATE_FORMAT(m.end_time,"%Y-%m-%d") end_time,m.is_have_time,m.remarks')->select();
        foreach ($tollBz as $key=>$value){
            if($value['is_have_time'] === 1) $tollBz[$key]['end_time'] = '无结束时间';
        }
        return __success('ok',['data'=>$info,'house_user'=>$houseUser,'car'=>$car,'bz'=>$tollBz]);
    }

    // 解绑用户
    public function untiedUser() {
        $car_area_id = $this->request->param('car_area_id'); // 车位id
        $house_user_id = $this->request->param('house_user_id'); // 住户id
        if(empty($car_area_id)) return __error('参数错误');
        if(empty($house_user_id)) return __error('参数错误');
        $delRes = Db::name('wy_houses_user_middle')->where(['car_area_id'=>$car_area_id,'house_user_id'=>$house_user_id])->delete();
        return !empty($delRes) ? __success('解绑成功') : __error('解绑失败');
    }

    // 解绑车辆
    public function untiedCar() {
        $id = $this->request->param('id'); // 车辆id
        if(empty($id)) return __error('参数错误');
        $upRes = Db::name('wy_car')->where('id',$id)->update(['car_area_id'=>null]);
        return $upRes !== false ? __success('解绑成功') : __error('解绑失败');
    }

    // 删除车位
    public function delParking() {
        $ids = $this->request->param('ids');
        if(empty($ids)) return __error('参数错误');
        // 判断当前车位下是否有住户
//        $user = Db::name('wy_houses_user_middle')->alias('m')->join('wy_car_area a','m.car_area_id = a.id')->where('m.car_area_id','in',$ids)->select();
//        foreach ($user as $key=>$value){
//            return __error('车位' . $value['name'] . '存在住户,不可删除');
//        }
        // 判断当前车位是否有车辆
        $car = Db::name('wy_car_area')->alias('a')->join('wy_car c','c.car_area_id = a.id')->where('a.id','in',$ids)->where('c.is_deleted','=',0)->field('a.id,a.name')->select();
        foreach ($car as $key=>$value){
            return __error('车位' . $value['name'] . '存在车辆,不可删除');
        }
        $delRes = Db::name('wy_houses_user_middle')->where('car_area_id','in',$ids)->delete();
//        if(empty($delRes)) return __error('住户解绑失败');
        $upRes = Db::name('wy_car_area')->where('id','in',$ids)->update(['is_deleted'=>1]);
        return $upRes !== false ? __success('删除成功') : __error('删除失败');
    }

    // 获取所有小区列表
    public function getAllCommunityList() {
        $where[] = ['is_deleted','=',0];
        $where[] = ['pms_ar_id','=',$this->userinfo['pms_ar_id']];
        if(@$this->userinfo['cm_message_id']){
            $where[] = ['id','in',$this->userinfo['cm_message_id']];
        }
        // 小区
        $list = Db::name('wy_bd_info')->where($where)->field('id value,name label')->select();
        return __success('ok',$list);
    }

    // 获取小区车位
    public function getAllCommunityParking() {
        $param = $this->request->param();
        $where[] = ['is_deleted','=',0];
        $where[] = ['pms_ar_id','=',$this->userinfo['pms_ar_id']];
        if($this->userinfo['cm_message_id']){
            $where[] = ['id','in',$this->userinfo['cm_message_id']];
        }
        // 小区
        $communityList = Db::name('wy_bd_info')->where($where)->field('id value,name label')->select();
        $communityIds = array();
        foreach ($communityList as $key=>$value) {
            array_push($communityIds,$value['value']);
            $communityList[$key]['id']=$value['value'];
        }
        // 车位
        $parkingList = Db::name('wy_car_area')->where('bd_info_id','in',$communityIds)->field('id value,name label,bd_info_id')->select();
        foreach ($communityList as $ck=>$cv){
            $communityList[$ck]['children'] = array();
            $communityList[$ck]['value'] = $ck.'-'.$cv['value'];
            foreach ($parkingList as $pk=>$pv){
                if($pv['bd_info_id'] === $cv['value']){
                    unset($pv['bd_info_id']);
                    array_push($communityList[$ck]['children'],$pv);
                }
            }
        }
        return __success('ok',$communityList);
    }

    // 获取车位为缴费账单
    // 获取车辆为缴费账单
    public function get_car_area_detail_nopay() {
        $param = $this->request->post();
        $data = Db::name('wy_no_payment')->where(['car_area_id' => $param['id'], 'pay_status' => 0])->select();
        $typetext = ['1' => '房屋', '2' => '车辆', '3' => '车位', '4' => '住户'];
        if(empty($data)) {
            return __error('暂无数据');
        } else {
            foreach($data as $k => $v) {
                $data[$k]['carArea_name'] = Db::name('wy_car_area')->where('id', $v['car_area_id'])->value('name');
                $data[$k]['type'] = $typetext[$v['type']];
            }
            return __success('查询成功', $data);
        }
    }
}